// 依赖文件 script/baseConfig.js; script/utils.js；
var ajaxErrorOptionArry = [];//ajax请求失败后临时放入这个变量

/*
	当前退出入口有：ajax当状态为401的时候会触发退出，用户进入设置页主动退出
	当前登录入口有：login登录3个（密码登录，QQ快速登录，微信快速登录），绑定手机1个，注册1个
*/

(function(window, undefined){
	var YY = {
		prefs: {  // 偏好设置，本地存储，替代localStorage;
			setItem: function(key, string){
				api.setPrefs({
					key: key,
					value: string
				});
			},
			getItem: function(key){
				var data = api.getPrefs({
					sync: true,
					key: key
				});
				if(data == ''){
					return null;
				}
				return data;
			},
			removeItem: function(key){
				api.removePrefs({
					key: key
				});
			},
		},
		handleLocalStorage: {
			get: function(key) {
				var value = YY.prefs.getItem(key);
				if (value) {
					try {
						var value_json = JSON.parse(value);
						return value_json;
					} catch(e) {
						return value;
					}
				} else {
					return false;
				}
			},
			set: function(key, value) {
				let transStrs = JSON.stringify(value);
				YY.prefs.setItem(key, transStrs);
			},
			remove: function(key) {
				YY.prefs.removeItem(key);
			},
			clear: function() {
				YY.prefs.clear();
			}
		},
		saveUser: function(data){
			YY.prefs.setItem(CONFIG.cacheKeys.USERINFO, JSON.stringify(data));
		},
		getUser: function(){
			return CONFIG.cacheKeys.USERINFO && JSON.parse(YY.prefs.getItem(CONFIG.cacheKeys.USERINFO)) || null;
		},
		removeUser: function(){
			YY.prefs.removeItem(CONFIG.cacheKeys.USERINFO);
		},
		isLogin:function(){
			return !!(YY.getUser() && YY.getUser().id > 0);
		},
		initJs(app){
			var url = CONFIG.httpConfig.oss + "/js/core.js?time=" + new Date().getTime();
			var script = document.createElement('script');
			script.type = 'text/javascript';
			script.src = url;
			script.onload = function(){init(app);};
			document.head.appendChild(script);
		},
		toast: function(msg){
			var options = {
				msg: '',
				duration: 2000,
				location: 'bottom'
			};
			if(Object.prototype.toString.call(msg) === '[object Object]'){
				options = msg;
			}else{
				options.msg = String(msg);
			}
			api.toast(options);
		},
		prompt:function(option){//只能用于2个按钮的情况
			api.prompt({
				title:option.title || "提示",
				msg:option.msg || "",
				text:option.text || "",
				type:option.type || "text",
				buttons: api.systemType=='ios'?option.buttons:[option.buttons[1],option.buttons[0]],
			}, function(ret, err) {
				var index = ret.buttonIndex;
				var text = ret.text;
				if(api.systemType=='ios'){
					if(index==1){
						option.error && option.error();
					}else if(index==2){
						option.success && option.success(text);
					}
				}else{
					if(index==1){
						option.success && option.success(text);
					}else if(index==2){
						option.error && option.error();
					}
				}
			});
		},
		alert: function(msg, callback){
			var options = {
				title: '提示',
				msg: 'testmsg',
			};
			if(Object.prototype.toString.call(msg) === '[object Object]'){
				options = msg;
			}else{
				options.msg = msg.toString();
			}
			api.alert(options, function(ret, err){
				callback && callback(ret, err);
			});
		},
		confirm:function(option){//只能用于2个按钮的情况
			api.confirm({
				title:option.title||"提示",
				msg: option.msg||"",
				buttons: api.systemType=='ios'?option.buttons:[option.buttons[1],option.buttons[0]],
			}, function(ret, err) {
				var index = ret.buttonIndex;
				if(api.systemType=='ios'){
					if(index==1){
						option.error && option.error();
					}else if(index==2){
						option.success && option.success();
					}
				}else{
					if(index==1){
						option.success && option.success();
					}else if(index==2){
						option.error && option.error();
					}
				}
			});
		},

		showLoad:function(option){
			api.showProgress({
				title: option.title || "",
				text: option.text || "",
				modal: option.modal || true
			});
		},
		hideLoad:function(){
			api.hideProgress();
		},

		showNoNetWork(){
			api.openFrame({
				name: "noNetwork",
				useWKWebView:true,
				url: 'widget://html/content/common/noNetwork.html',
				bgColor: 'rgba(0,0,0,0)',
				animation:{
					type:"fade"
				},
			});
		},
		rect: function(){
			var rect = {
				marginTop:0,
				marginBottom:0,
			}
			if(document.querySelectorAll("#header").length>0){
				document.querySelector("#header").style.paddingTop = api.safeArea.top + "px";
				rect.marginTop = document.querySelector("#header").offsetHeight;
			}

			if(document.querySelectorAll("#footer").length>0){
				document.querySelector("#footer").style.paddingBottom = api.safeArea.bottom + "px";
				rect.marginBottom = document.querySelector("#footer").offsetHeight;
			}
			return rect;
		},

		// 默认跳转页面
		openUrl: function(headerName,contentName,data){
			//不处于白名单，并且未登录状态
			if(CONFIG.noMustLogin.indexOf(contentName)==-1 && !YY.isLogin() && headerName != 'common/outUrlCommonTitle'){
				$.openUrl('common/commonUser','common/login');
				return;
			}

			if(!contentName){contentName = headerName;}
			api.openWin({
				name: contentName,
				url: 'widget://html/head/' + headerName + '.html',
				slidBackEnabled: (data && data.slidBackEnabled!=undefined) ? data.slidBackEnabled : true,
				slidBackType:"edge",
				pageParam: {
					page: contentName,
					data: data || {}
				},
				useWKWebView:true,
				animation:(data && data.animation) || {}
			});
		},

		getHeaders: function(headers,type){
			headers = headers || {};
			if(YY.isLogin()){headers['Authorized-Key'] =  YY.getUser().authorized_key;}
			headers['User-Agent'] = window.navigator.userAgent;
			headers['systemType'] = api.systemType;
			headers['systemVersion'] = api.systemVersion;
			headers['deviceModel'] = api.deviceModel;
			headers['deviceId'] = api.deviceId;
			headers['date'] = new Date().getTime();
			headers['appVersion'] = api.appVersion;
			headers['time'] = md5('qian~@%$TY$U)'+api.systemType+'fengwo'+api.systemVersion+'bang...'+api.deviceModel+'yixia~!@#'+api.deviceId+'ba'+api.appVersion+'hou*/-----' + headers['date']);
			headers['isSimulator'] = YY.prefs.getItem("isSimulator") || '0';
			headers['appVerMd5'] = md5('isDog?)' + api.deviceModel + headers['isSimulator'] +'is*/-----' + headers['date']);
			if(type=="param"){
				var queryPar = null;
				for(key in headers){
					var cache = key;
					if(key == "User-Agent"){
						continue;
					}else if(key == "Authorized-Key"){
						cache = "token";
					}
					var addPar =  cache + '=' + encodeURIComponent(headers[key]);
					queryPar = queryPar ? queryPar + '&' + addPar : addPar;
				}
			}
			return type=='param'?queryPar:headers;
		},
		
		isSimulator:function(){
			var cis = api.require('isSimulator');
			cis.isSimulator(function(ret, err){
				if(ret.code == 200){
					if(ret.value.isVirtual){
						YY.prefs.setItem("isSimulator","1");
					}else{
						YY.prefs.setItem("isSimulator","2");
					}
				}else{
					YY.prefs.setItem("isSimulator","0");
				}
			});
		},

		// 网络请求
		ajax: function(option){
			option.load && api.showProgress({
				title: '',
				text: ''
			});
			var optionData = {};
			if (option.data) {
				if (option.data.values) {
					optionData.values = option.data.values;
				}
				if (option.data.files) {
					optionData.files = option.data.files;
				}
				if (!option.data.values && !option.data.files) {
					optionData.values = option.data;
				}
			}
			api.ajax({
				url: option.baseUrl || (CONFIG.httpConfig.host[CONFIG.env]+ "/api/app" + (option.url || "")),
				method: option.method || 'get',
				dataType: option.dataType || 'json',
				timeout: option.timeout || 10,
				headers: YY.getHeaders(option.headers),
				data: optionData,
				tag: option.tag
			}, function(ret, err) {
				api.refreshHeaderLoadDone();//管他有不有下拉刷新，都给他关了。
				if(option.autoCloseLoad!=false){
					option.load && api.hideProgress();
				}

				if (ret) {
					//console.log(JSON.stringify(ret.code))
					if(ret.code==0){
						option.success && option.success(ret);
					}else{
						if(ret.code == 401){
							YY.removeUser();
							YY.alert(ret.message,function(){
								api.sendEvent({name: 'reshIndexBasic'});//刷新首页基本信息，比如红包样式
								api.sendEvent({name: 'loginExit'});//让任务页的数字以及任务页面显示未登录状态。
								
								api.sendEvent({  //让我的页面刷新
									name: 'navGetData',
									extra: {navIndex:3}
								});
								api.sendEvent({  //回到我的
									name: 'backIndex',
									extra: {navIndex:3}
								});
							})
						}
						if(option.error){
							option.error && option.error(ret);
						}else{
							YY.toast(ret.message);
						}
					}
				} else {
					console.log(err.body);
					if(option.servceLayer!=false){
						ajaxErrorOptionArry.push(option);
						if(ajaxErrorOptionArry.length==1){
							YY.confirm({
								title: '提示',
								msg: '网络异常',
								buttons: ['取消','重试'],
								success:function(){
									YY.reNet();
								},
								error:function(){
									ajaxErrorOptionArry = [];
								}
							});
						}
					}
					//YY.showNoNetWork();
				}
				option.done && option.done(ret,err);
			});
		},
		reNet(){//重新加载网络
			for(var i in ajaxErrorOptionArry){
				YY.ajax(ajaxErrorOptionArry[i]);
			}
			ajaxErrorOptionArry = [];
		},

		/**
		 *  通用请求方法
		 *  @param { String } method 请求方式
		 *  @param { String } url 请求路径
		 *  @param { Object } resPar 请求参数
		 *  @param { Function } resolve 成功回调
		 *  @param { Function } reject 失败回调
		 */
		comRequest: function (method,url,resPar,resolve,reject,load,autoCloseLoad) {
			method = method || 'get';
			let baseUrl = url;
			let ajaxPar = {
				method: method,
				load:load||false,
				autoCloseLoad:autoCloseLoad==0?false:true,
				success: function(res) {
					resolve(res);
				},
				error: function(ero) {
					reject(ero)
				}
			}
			//  url: `/task/accept/my?page=${page}&status=${status}`,
			if (method === 'get' && JSON.stringify(resPar) !== '{}') {
				let queryPar = null;
				for(key in resPar){
					let addPar =  key + '=' + resPar[key];
					queryPar = queryPar ? queryPar + '&' + addPar : addPar;
				}
				baseUrl = baseUrl + '?' + queryPar;
			}
			if (method === 'post' && JSON.stringify(resPar) !== '{}') {
				ajaxPar.data = resPar;
			}
			ajaxPar.url = baseUrl;
			$.ajax(ajaxPar);
		},

		//金额转换
		parsePrice: function(price, float){
			
			float = typeof float === 'undefined' ? 2 : parseInt(float);
			price = price / CONFIG.PRICE_RADIO;
			var priceStr = price.toString();
			var dotIndex = priceStr.indexOf('.');
			var rightPad = new Array(float+1).join('0');

			if(dotIndex < 0){
				return price.toFixed(float);
			}else{
				if(float==0){
					return (priceStr + rightPad).substring(0, dotIndex);
				}else{
					return (priceStr + rightPad).substring(0, dotIndex + 1 + float);
				}
			}
		},
		yuanToSys: function(m){
			var money = parseFloat(m);
			money = isNaN(money) ? 0 : money;
			return money * CONFIG.PRICE_RADIO;
		},

		//下拉刷新
		pullDown: function(option){
			var cvVibrate = api.require('cvVibrate');
			var pullImgs = [];
			var loadImgs = [];
			for(var i=0; i<8; i++){
				pullImgs.push('widget://image/animates/ae'+(i+1)+'.png');
			}
			api.setCustomRefreshHeaderInfo({
				bgColor: option.bgColor || '#F9F9F9',
				isScale: true,
				image: {pull: pullImgs,load: pullImgs}
			}, function() {
				cvVibrate.Peek();
				option.success() && option.success();
			});
		},
		/**
		 *  获取上传前缀
		 * @param { Sring } uploadType 上传属性 默认Task, 头像Avatar，使用baseConfig里的常量配置。
		 * @param { String } fileType 文件属性 img, video
		 */
		createUploadPrefix: function (uploadType, fileType) {
			uploadType = uploadType || CONFIG.constants.TASK;
			fileType = fileType || 'img';
			var prefix = uploadType;
			if (CONFIG.env == 'dev') {
				if (fileType === 'img') {
					prefix ='TestG'
				}
				if (fileType === 'video') {
					prefix ='TestV'
				}
			}
			return prefix;
		},
		createBid: function () {
			var bid = '';
			try {
				bid +=  md5(Date.now().toString() + uuid.v1());
			}catch(ero){
				console.log(ero);
			}
			return bid;
		},
		// 创建文件上传的bid
		createBidFn: function(uploadType, fileType) {
			fileType = fileType || 'img'
			var prefix = uploadType;
			if (CONFIG.env == 'dev') {
				if (fileType === 'img') {
					prefix ='TestG'
				}
				if (fileType === 'video') {
					prefix ='TestV'
				}
			}
			var bid = prefix + '-';
			try {
				bid +=  md5(Date.now().toString() + uuid.v1());
			}catch(ero){
				console.log(ero);
			}
			return bid;
		},

		//打开右下角红包
		openLucyIcon:function(){
			var dWidth = document.documentElement.clientWidth;
			var px = dWidth * 100 / 750;
			var h = (px * 1.16);//红包高度
			var w = (px * 1.6);//红包宽度
			var footerH = px + api.safeArea.bottom;//底部导航栏高度
			api.openFrame({
				name: "luckIcon",
				useWKWebView:true,
				url: 'widget://html/content/common/luckIcon.html',
				bgColor: 'rgba(0,0,0,0)',
				rect:{ //20代表预留20px,避免仅靠页面边边
					x:api.winWidth - w - 20,
					y:api.winHeight - h - footerH - 20,
					h:h,
					w:w,
				},
				animation:{
					type:"fade"
				},
			});
		},

		//打开更新提示
		openUpdateLayer:function(result){
			var that = this;
			api.openFrame({
				name: "updateLayer",
				useWKWebView:true,
				url: 'widget://html/content/common/updateLayer.html',
				bgColor: 'rgba(0,0,0,0)',
				animation:{
					type:"fade"
				},
				pageParam:result
			});
		},

		//打开公告
		openNotice:function(str){
			var that = this;
			api.openFrame({
				name: "notice",
				useWKWebView:true,
				url: 'widget://html/content/common/notice.html',
				bgColor: 'rgba(0,0,0,0)',
				animation:{
					type:"fade"
				},
				pageParam:{
					str:str
				}
			});
		},

		//检查并更新
		checkUpdate:function(){
			var mam = api.require('mam');
			mam.checkUpdate(function(ret, err){
				if (ret) {
					var result = ret.result;
					if (result.update == true && result.closed == false) { //非强制更新
						YY.openUpdateLayer(result);
						api.sendEvent({name: 'updateAleady',extra: {result:result}});
					} else if(result.update == true  && result.closed == true ) { //强制更新
						YY.openUpdateLayer(result);
						api.sendEvent({name: 'updateAleady',extra: {result:result}});
					} else if(result.update == false  && result.closed == true ) { //无更新，强制关闭本版本
						$.alert('本APP版本已被后台关闭，请找官方寻找最新下载包',function(){
							api.closeWidget({
								silent:true
							});
						});
					} else if(result.update == false  && result.closed == false ) { //无更新
						console.log("当前版本已是最新版。");
					}
				} else {
					console.log("更新检查失败：" + err.msg);
				}
			});
		},
		saveMediaToAlbum: function(file, cb){
			var reg = /\.([0-9a-z]+)(?:[\?#]|$)/i;
			var ext = file.match(reg)[1];
			var path = 'fs://Fwb'+Date.now()+'.'+ext;
			api.download({
				url: file,
				savePath: path,
				cache: true,
				allowResume: true
			}, function(ret, err) {
				if (ret.state == 1) {
					api.saveMediaToAlbum({
						path: path,
					},function(ret, err){
						if(ret.status){
							cb && cb();
						}
					});
				}
			});
		},
	};
	window.$ = window.YY = YY;
})(window, undefined);
